from messaging import AlarmEvent
from threading import Thread, Event
import hashlib
import time
import urllib
import wx
        
class Spirit(Thread):
    windowRef = None
    
    def __init__(self, windowRef, conf):
        Thread.__init__(self)
        
        self.url = conf["url"]
        self.delay = int(conf["delay"])
        if 'hash' in conf:
            self.hash = conf['hash']
            self.date = conf['date']
        else:
            self.hash = None
         
        if not self.windowRef:
            Spirit.windowRef = windowRef
            
        self.__delayevent = Event()
        self.__pauseevent = Event()
        self.__exit = False
        
    def getHash(self):
        f = urllib.urlopen(self.url)
        s = f.read()
        f.close()
        m = hashlib.md5(s)
        return m.hexdigest()
    
    def run(self):
        #wx.PostEvent(self.windowRef, AlarmEvent(self))
        #return    
        while(not self.__exit):
            if self.hash:
                h = self.getHash()
                
                if h != self.hash:
                    #print "%s - %s" % (h, self.__hash)
                    wx.PostEvent(self.windowRef, AlarmEvent(self))
                    #return
            else:
                #prendi l'hash e la data di riferimento (i dati attuali)
                self.hash = self.getHash()
                self.date = time.strftime("%d-%m-%Y %H:%M:%S", time.localtime())
                self.windowRef.updateItemList(self, self.date)
                
            self.__delayevent.wait(self.delay)# *60
            self.__pauseevent.wait()
            
    def pause(self):
        self.__pauseevent.clear()
        self.__delayevent.set()
    
    def resume(self):
        self.__delayevent.clear()
        self.__pauseevent.set()
        
    def terminate(self):
        """settando i 2 eventi, ci si assicura che il thread non rimanga in
        attesa. exit a true fa poi uscire dal ciclo """
        self.__exit = True
        self.__delayevent.set()
        self.__pauseevent.set()

    def __repr__(self):
        return "{%s %s}" % (self.url, self.delay)
    
    def __str__(self):
        ret = "%s,%s" % (self.url, self.delay)
        if self.hash:
            ret += ",%s,%s" % (self.hash, self.date)
        return ret